﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Trade.Journal.Controls
{
    public class NumberBox : TextBox
    {
        public static readonly Key[] Avaliable = { Key.Enter, Key.Left, Key.Right, Key.Back, Key.Clear, Key.Delete, /*Key.OemPeriod, Key.Decimal*/ };


        static NumberBox()
        {
            TextProperty.OverrideMetadata(typeof(NumberBox), new FrameworkPropertyMetadata(null, 
                FrameworkPropertyMetadataOptions.AffectsRender, null, new System.Windows.CoerceValueCallback(OnText), false, System.Windows.Data.UpdateSourceTrigger.PropertyChanged));
        }

        private static object OnText(DependencyObject d, object baseValue)
        {
            if (baseValue != null && baseValue.ToString().Trim() == "0")
                return null;
            else
                return baseValue;
        }



        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) ||
                (e.Key >= Key.D0 && e.Key <= Key.D9) || Avaliable.Contains(e.Key) || CanInputPeriod(e.Key))
                base.OnPreviewKeyDown(e);
            else
                e.Handled = true;
        }

        protected override void OnPreviewKeyUp(KeyEventArgs e)
        {
            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) ||
                   (e.Key >= Key.D0 && e.Key <= Key.D9) || Avaliable.Contains(e.Key) || CanInputPeriod(e.Key))
                base.OnPreviewKeyUp(e);
            else
                e.Handled = true;
        }

        private bool CanInputPeriod(Key key)
        {
            if (Text == null)
                return true;
            else if (!Text.Contains('.') && (key == Key.Decimal || key == Key.OemPeriod))
                return true;
            else return false;
        }
    }
}
